package com.community.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.community.common.mapper.UserPermissionMapper;
import com.community.common.pojo.constant.WeChatConstant;
import com.community.common.pojo.domain.PublicUser;
import com.community.common.pojo.domain.UserPermission;
import com.community.common.pojo.response.MyResponse;
import com.community.common.service.MyWXService;
import com.community.common.service.OwnerHouseService;
import com.community.common.service.UserPermissionService;
import com.community.common.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号调用控制器
 * <p>
 * Created by Enzo Cotter on 2020/9/8.
 */
@Slf4j
@Controller
@RequestMapping("/wx")
public class WXController {

    @Resource
    private WxMpService wxMpService;
    @Resource
    private MyWXService myWxService;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private UserPermissionService userPermissionService;

    @Resource
    OwnerHouseService ownerHouseService;

    @Autowired
    private WxUtil wxUtil;

    /**
     * 验证是否来自微信服务器的消息get
     */
    @GetMapping("/check")
    @ResponseBody
    public String checkSignature(@RequestParam(name = "signature", required = false) String signature,
                                 @RequestParam(name = "nonce", required = false) String nonce,
                                 @RequestParam(name = "timestamp", required = false) String timestamp,
                                 @RequestParam(name = "echostr", required = false) String echostr) {
        boolean result = wxMpService.checkSignature(timestamp, nonce, signature);
        return result ? echostr : null;
    }

    /**
     * 此处是处理微信服务器的消息转发的
     */
    @PostMapping("/check")
    @ResponseBody
    public String processMsg(HttpServletRequest request) {
        // 调用核心服务类接收处理请求
        return myWxService.processRequest(request);
    }

    /**
     * 获取openId与subscribe（是否关注了公众号）
     */
    @GetMapping("/getOpenIdBaseInfo")
    @ResponseBody
    public MyResponse getOpenIdBaseInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String openId = (String) session.getAttribute(WeChatConstant.OPENID);
        try {
            if (StringUtils.isEmpty(openId)) {
                wxUtil.requestOpenId(request, response);
            } else {
                // 根据openId判断用户是否关注了公众号
                if (wxUtil.isSubscribe(openId)) { // 关注了公众号
                    session.setAttribute(WeChatConstant.SUBSCRIBE, "1");
                } else { // 未关注公众号
                    session.setAttribute(WeChatConstant.SUBSCRIBE, "0");
                }
            }
        } catch (Exception e) {
            log.error("获取openId 或 处理是否关注了公众号 error", e);
            return MyResponse.fail();
        }
        // 处理需要返回的信息字段
        Map<String, String> map = new HashMap<>();
        map.put(WeChatConstant.OPENID, openId); // openId
        // 是否关注公众号
        map.put(WeChatConstant.SUBSCRIBE, (String) session.getAttribute(WeChatConstant.SUBSCRIBE));
        return MyResponse.success(map);
    }

    /**
     * 获取openId的授权回调，存在session中保持一致
     */
    @ResponseBody
    @GetMapping("/OpenIdHandler")
    public String wxOauth(HttpServletRequest request, String fromUrl) {
        String code = request.getParameter("code");
        log.info("code：{}", code);
        // 是否关注了公众号
        String openId = null;
        try {
            // 通过code去换取access_token
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            openId = wxMpOAuth2AccessToken.getOpenId();
        } catch (WxErrorException e) {
            log.error("通过code获取openId失败：{}", e.getMessage());
            return "getError";
        }
        if (StringUtils.isNotEmpty(openId)) {
            request.getSession().setAttribute(WeChatConstant.OPENID, openId); // openId
        }
        log.info("授权回调地址：{}", fromUrl);
        return "redirect:" + fromUrl;
    }

    /**
     * 获取js调用凭证
     */
    @GetMapping("/getJsSDKConfig")
    @ResponseBody
    public MyResponse getJsSDKConfig(@RequestParam("url") String url) {
        WxJsapiSignature jsapiSignature = null;
        try {
            jsapiSignature = wxMpService.createJsapiSignature(url);
            return MyResponse.success(jsapiSignature);
        } catch (Exception e) {
            log.error("获取js调用凭证 getJsSDKConfig error ", e);
            return MyResponse.fail();
        }
    }

    /**
     * 通过code获取openId和基本信息
     */
    @GetMapping("/getOpenIdBaseInfoByCode")
    @ResponseBody
    public MyResponse getOpenIdBaseInfoByCode(String code, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String openId = null;
        try {
            // 通过code去换取access_token
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            openId = wxMpOAuth2AccessToken.getOpenId();
            if (StringUtils.isEmpty(openId)) {
                return MyResponse.fail("获取openId失败");
            }
            // 根据openId判断用户是否关注了公众号
            if (wxUtil.isSubscribe(openId)) { // 关注了公众号
                session.setAttribute(WeChatConstant.SUBSCRIBE, "1");
            } else { // 未关注公众号
                session.setAttribute(WeChatConstant.SUBSCRIBE, "0");
            }
        } catch (Exception e) {
            log.error("获取openId 或 处理是否关注了公众号 error", e);
            return MyResponse.fail();
        }
        // 处理需要返回的信息字段
        Map<String, String> map = new HashMap<>();
        map.put(WeChatConstant.OPENID, openId); // openId
        map.put(WeChatConstant.SUBSCRIBE, (String) session.getAttribute(WeChatConstant.SUBSCRIBE)); // 是否关注公众号
        return MyResponse.success(map);
    }

    /**
     * 获取用户角色
     */
    @GetMapping("/getRole")
    @ResponseBody
    public MyResponse getRole(String openId) {
        return MyResponse.success("获取成功", ownerHouseService.checkByOpenId(openId));
    }

    /**
     * 获取用户相机权限
     */
    @GetMapping("/getPermission")
    @ResponseBody
    public MyResponse getPermission(String openId) {
//        LambdaQueryWrapper<PublicUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(PublicUser::getOpenId, openId);
//        UserPermission userPermission = userPermissionMapper.selectByOpenId(openId);
//        return MyResponse.success("获取成功", userPermissionService.getPermission(userPermission));
        return MyResponse.success();
    }

}
